package com.zlx.exchange.user.controller;


import cn.hutool.jwt.JWT;
import com.alibaba.nacos.common.utils.StringUtils;
import com.github.pagehelper.util.StringUtil;
import com.zlx.exchange.domain.entity.User;
import com.zlx.exchange.user.service.UserService;
import org.hamcrest.text.IsBlankString;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2023-09-04 18:59:36
 */
@RestController
@CrossOrigin
@RequestMapping("api/user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 登录，并创建jwt
     *
     * @param  user
     * @return
     */
    @PostMapping("loginByUserName")
    public ResponseEntity<?> loginByUserName(@RequestBody User user) {
        System.out.println("user:" + user);
        User user1 = userService.queryByUsername(user.getUsername(),  user.getPassword());
        if (Objects.isNull(user1)) {
            return ResponseEntity.status(1).body("账号或密码错误");
        }
        String jwt = JWT.create().setKey(user1.getUserKey().getBytes())
                .setPayload("userId",user1.getId())
                .setPayload("username", user1.getUsername())
                .setPayload("role", user1.getRoleId())
//                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 30))
                .sign();
        redisTemplate.opsForValue().set("user" + user1.getId(), jwt);

        return ResponseEntity.ok().body(jwt);
    }

    @PostMapping("register")
    public ResponseEntity<?> register(String username, String password) {
        if (StringUtils.isAnyBlank(username, password)) {
            return ResponseEntity.status(2).body("不可为空");
        }
        if (userService.register(username, password)) {
            return ResponseEntity.ok("注册成功");
        }
        else {
            return ResponseEntity.status(3).body("注册失败");
        }
    }
}

